package com.oe.user.controller;

import com.oe.code.CodeService;
import com.oe.code.req.CheckCodeReq;
import com.oe.code.resp.CheckCodeResp;
import com.oe.lang.build.ResponseBuilder;
import com.oe.lang.resp.LdmResponse;
import com.oe.user.dao.LagouTokenDao;
import com.oe.user.model.LagouToken;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@RestController
public class UserController {

    @Autowired
    LagouTokenDao lagouTokenDao;

    @Reference(check = false)
    CodeService codeService;



    @RequestMapping(value = "/api/user/register/{email}/{password}/{code}")
    public LdmResponse registerUser(HttpServletResponse response, @PathVariable("email") String email, @PathVariable("password") String password, @PathVariable("code") String code){
        CheckCodeReq req = new CheckCodeReq();
        req.setCode(code);
        req.setEmail(email);
        CheckCodeResp checkCodeResp = codeService.checkCode(req);
        if (!checkCodeResp.getSuccess()){
            return ResponseBuilder.buildResponse(false,"500","验证码不正确或已过期！",null);
        }
        LagouToken lagouAuthCode = new LagouToken();
        lagouAuthCode.setEmail(email);
        lagouAuthCode.setToken(email+password);
        lagouTokenDao.save(lagouAuthCode);
        Cookie cookie = new Cookie("token",email+password);
        cookie.setMaxAge(60*30);
        response.addCookie(cookie);
        return ResponseBuilder.buildResponse(true,"200","注册成功！",lagouAuthCode);
    }

    @RequestMapping(value = "/api/user/login/{email}/{password}")
    public LdmResponse login(HttpServletResponse response,@PathVariable("email") String email, @PathVariable("password") String password){
        LagouToken lagouAuthCode = lagouTokenDao.findByTokenEquals(email + password);
        if(lagouAuthCode==null){
            return ResponseBuilder.buildResponse(false,"500","账号或密码不正确！",null);
        }
        Cookie cookie = new Cookie("token",email+password);
        cookie.setMaxAge(60*30);
        response.addCookie(cookie);
        return ResponseBuilder.buildResponse(true,"200","登陆成功！",lagouAuthCode);
    }

    @RequestMapping("/api/user/info/{token}")
    public LdmResponse getUserInfo(@PathVariable("token") String token){
        LagouToken lagouAuthCode = lagouTokenDao.findByTokenEquals(token);
        if(lagouAuthCode==null){
            return ResponseBuilder.buildResponse(false,"500","当前token的用户不存在!!!",null);
        }
        return ResponseBuilder.buildResponse(true,"200",null,lagouAuthCode.getEmail());
    };
}
